package mapred.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class Links {

    private static final String DELIM = "#";

    private Map<String, Integer> map;

    private Links(Map<String, Integer> map) {
        this.map = map;
    }

    public static Links parse(String line) {
        Links ret = Links.createNewLinks();
        String[] targets = line.split("\t");
        for (String target : targets) {
            String[] t = target.split(DELIM);
            String k = t[0];
            if (t.length > 1) {
                int v = Integer.parseInt(t[1]);
                ret.addTarget(k, v);
            } else {
                ret.addTarget(k);
            }
        }
        return ret;
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (String k : map.keySet()) {
            sb.append(k);
            long v = map.get(k);
            if (v != 1) {
                sb.append(DELIM);
                sb.append(v);
            }
            sb.append("\t");
        }
        return sb.toString().trim();
    }

    public void add(Links... maps) {
        for (Links a : maps) {
            for (String k : a.map.keySet()) {
                this.addTarget(k, a.map.get(k));
            }
        }
    }

    public static Links createNewLinks() {
        return new Links(new HashMap<String, Integer>());
    }

    public void addTarget(String target) {
        this.addTarget(target, 1);
    }

    public void addTarget(String target, int value) {
        if (!target.isEmpty()) {
            if (map.containsKey(target)) {
                map.put(target, map.get(target) + value);
            } else {
                map.put(target, value);
            }
        }
    }

    public Set<String> targets() {
        return map.keySet();
    }

    public int getWeight(String target) {
        return map.get(target);
    }

    public boolean isEmpty() {
        return map.isEmpty();
    }

    public int size() {
        return map.size();
    }

}
